package com.project.service.impl;



import com.project.bean.InfoBean;
import com.project.bean.MQBean;
import com.project.bean.NewsEntity;
import com.project.bean.ShopBean;
import com.project.config.RedisCacheUtil;
import com.project.service.IShopService;
import com.rabbitmq.client.Channel;
import org.redisson.api.RLock;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class RabbitMQService {
  @Autowired
  RedisCacheUtil redisCacheUtil;
  @Autowired
  IShopService service;
  @Autowired
  RLock rLock;

  public static  int nums=10;

  @RabbitListener(queues = "infoQueue")
  public void message(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, InfoBean infoBean) throws IOException, InterruptedException {
    //随机数
    if (nums>0) {
      boolean bl = rLock.tryLock(0, 10, TimeUnit.SECONDS);
      if (bl) {
        int num = (int) (Math.random() * 5);
        if (num < 3) {
          ShopBean shopBean = new ShopBean();
          shopBean.setName(infoBean.getName());
          shopBean.setImg("7.jpg");
          shopBean.setPrice(infoBean.getPrice());
          shopBean.setUserName(infoBean.getUserName());
          service.add(shopBean);
          redisCacheUtil.hset(infoBean.getUserName(), infoBean.getOrderNum(), infoBean);
          redisCacheUtil.set("num", nums);
          redisCacheUtil.set("info", "1");
          nums--;
          System.out.println(nums);
        }
        rLock.unlock();//释放锁
      }
      //手动确认
    }
    channel.basicAck(tag,false);

  }

}
